from django.views.generic.base import View

from goods.models import Goods


class GoodsListView(View):
    def get(self, request):
        """
        通过django的view实现商品列表页
        :param request:
        :return:
        """
        json_list = []
        goods = Goods.objects.all()[:10]
        # for good in goods:
        #     json_dict = {
        #         "name": good.name,
        #         "category": good.category,
        #         "market_price": good.market_price
        #     }
        #     json_list.append(json_dict)

        # django自带字段转dict
        # from django.forms.models import model_to_dict
        # for good in goods:
        #     json_dict = model_to_dict(good)
        #     json_list.append(json_dict)

        # 为解决如日期，图片等字段带来的无法序列化问题，可使用如下方法from django.core import serializers
        from django.core import serializers
        import json
        json_data = serializers.serialize("json", goods)
        json_data = json.loads(json_data)
        from django.http import HttpResponse, JsonResponse
        return JsonResponse(json_data, safe=False)
